package org.wmq.positiontoshop.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.wmq.positiontoshop.model.DO.Shop;
import org.wmq.positiontoshop.model.ES.ShopES;
import org.wmq.positiontoshop.repository.ShopESRepository;

/**
 * Elasticsearch数据同步服务
 * 用于处理数据库和Elasticsearch之间的数据同步
 */
@Service
@Slf4j
public class ElasticsearchSyncService {
    
    @Autowired
    private ShopESRepository shopESRepository;
    
    @Autowired
    private ShopService shopService;
    
    /**
     * 将店铺数据同步到Elasticsearch
     * 
     * @param shopId 店铺ID
     */
    @Async("taskExecutor")
    public void syncShopToES(Long shopId) {
        try {
            Shop shop = shopService.getById(shopId);
            if (shop != null) {
                ShopES shopES = ShopES.fromDO(shop);
                shopESRepository.save(shopES);
                log.info("成功同步店铺数据到Elasticsearch，shopId={}", shopId);
            } else {
                log.warn("店铺不存在，无法同步到Elasticsearch，shopId={}", shopId);
            }
        } catch (Exception e) {
            log.error("同步店铺数据到Elasticsearch失败，shopId={}", shopId, e);
            throw new RuntimeException("同步店铺数据到Elasticsearch失败", e);
        }
    }
    
    /**
     * 从Elasticsearch删除店铺数据
     * 
     * @param shopId 店铺ID
     */
    @Async("taskExecutor")
    public void deleteShopFromES(Long shopId) {
        try {
            shopESRepository.deleteById(shopId);
            log.info("成功从Elasticsearch删除店铺数据，shopId={}", shopId);
        } catch (Exception e) {
            log.error("从Elasticsearch删除店铺数据失败，shopId={}", shopId, e);
            throw new RuntimeException("从Elasticsearch删除店铺数据失败", e);
        }
    }
    
    /**
     * 初始化Elasticsearch数据
     * 将数据库中的所有店铺数据同步到Elasticsearch
     */
    public void initElasticsearchData() {
        try {
            log.info("开始初始化Elasticsearch数据");
            // 清空现有索引
            shopESRepository.deleteAll();
            
            // 分批获取数据库中的店铺数据并同步到ES
            // 这里简化处理，直接获取所有店铺
            for (Shop shop : shopService.list()) {
                ShopES shopES = ShopES.fromDO(shop);
                shopESRepository.save(shopES);
            }
            
            log.info("Elasticsearch数据初始化完成");
        } catch (Exception e) {
            log.error("Elasticsearch数据初始化失败", e);
            throw new RuntimeException("Elasticsearch数据初始化失败", e);
        }
    }
}